package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.service.FileService;
import com.atguigu.srb.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        // 1.创建实例
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET
        );
        // @TODO 后续需要调整，目前不支持创建bucket，会报错，可能是api的问题
        // The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
        // 2.判断bucket是否存在
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)) {
            // 创建bucket
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            // 修改权限
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
        // 3.构建路径及文件名
        // 构建日期路径
        String folder = new DateTime().toString("yyyy/MM/dd");
        // 构建文件名
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        // 文件根路径
        String key = module + "/" + folder + "/" + fileName;
        // 4.上传
        ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);
        // 5.关闭实例
        ossClient.shutdown();

        // 6.返回地址
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + key;
    }

    @Override
    public void remove(String url) {
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET
        );
        // https://srb-file-200921.oss-cn-beijing.aliyuncs.com/
        // test/2021/02/27/f1673221-efb4-4356-98f4-9f0595caa927.jpg
        String host = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/";
        String objectName = url.substring(host.length());

        // 删除文件，如需删除文件夹，请将objectName设置为对应的文件名称，如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);

        // 关闭
        ossClient.shutdown();

    }
}
